import siteInfo from '../siteInfo'
import Md5 from 'md5'
import qs from 'qs'

const TOKEN = 'shanxikuyuanwangluokeji'

/**
 * 返回请求url
 */
function getUrl (action) {
  return siteInfo.siteroot + '?i=' + siteInfo.uniacid + '&t=' + siteInfo.multiid + '&v=' + siteInfo.version + '&kv=v1&from=wxapp&c=entry&a=wxapp&do=api&m=kuyuan_stall'
}

/**
 * 获取请求sign
 * @param param
 * @returns {*}
 */
function getSign (param) {
  let keys = Object.keys(param).sort()
  // eslint-disable-next-line camelcase
  let key_str = ''
  for (let i = 0; i < keys.length; i++) {
    // eslint-disable-next-line camelcase
    key_str += keys[i]
  }
  // eslint-disable-next-line camelcase
  key_str += TOKEN
  return Md5(key_str).toUpperCase()
}

const url = function (action, param) {
  let actions = action.split('/')
  let params = Object.assign({pages: actions[0], doing: actions[1]}, param)
  params.sign = getSign(params)
  return new Promise((resolve, reject) => {
    mpvue.request({
      url: getUrl(action),
      data: qs.stringify(params),
      method: 'POST',
      header: {'content-type': 'application/x-www-form-urlencoded'},
      timeout: 20000,
      success: function (res) {
        resolve(res)
      },
      fail: function (res) {
        reject(res)
      }
    })
  })
}

export default url
